<script setup>
import { Plus, Delete, Edit } from '@element-plus/icons-vue'
import { ref, defineEmits } from 'vue'

import {
  getCarouselListApi,
  deleteCarouselApi,
  getCarouselByIdApi,
  addCarouselApi,
  updateCarouselApi
} from '@/apis/carousel'
import { uploadFileApi } from '@/apis/common'
const emit = defineEmits(['title'])
emit('title', '轮播图管理')
const params = ref({
  pageNo: 1,
  pageSize: 10
})
const total = ref(0)

const tableData = ref([])
const columns = [
  {
    prop: '',
    type: 'selection'
  },
  {
    prop: '',
    type: 'index',
    label: '序号',
    width: '100'
  },
  {
    label: '轮播图',
    prop: 'carouselUrl',
    type: 'img',
    config: {
      width: '6.5rem',
      height: '5.8rem'
    }
  },
  {
    label: '跳转地址',
    prop: 'redirectUrl',
    type: 'link',
    lineClamp: 3
  },
  {
    label: '排序值',
    prop: 'carouselRank'
  },
  {
    prop: 'createTime',
    label: '创建时间',
    type: 'date'
  },
  {
    prop: '',
    type: 'operate',
    label: '操作'
  }
]
const getCarouselList = async () => {
  const res = await getCarouselListApi(params.value)
  tableData.value = res.data.data.list
  total.value = res.data.data.total
}
getCarouselList()

// 切换页大小
const sizeChange = (e) => {
  params.value.pageSize = e
  params.value.pageNo = 1
  getCarouselList()
}

// 切换页码
const currentChange = (e) => {
  params.value.pageNo = e
  getCarouselList()
}

const ids = ref([])
const onDelete = async (id) => {
  if (id) {
    ids.value = []
    ids.value.push(id)
  }
  if (ids.value.length <= 0) {
    ElMessage({
      message: '请选择要删除的数据',
      type: 'warning'
    })
    return
  }

  await ElMessageBox.confirm('确定删除吗？', '温馨提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })

  await deleteCarouselApi(ids.value)
  params.value.pageNo = 1
  ElMessage({
    message: '删除成功',
    type: 'success'
  })
  getCarouselList()
}

const formRef = ref(null)

const formData = ref({
  id: '',
  carouselUrl: '',
  redirectUrl: '',
  carouselRank: 0
})

const formRules = {
  carouselUrl: [
    { required: true, message: '请输入轮播图地址', trigger: 'blur' }
  ],
  redirectUrl: [{ required: true, message: '请输入跳转地址', trigger: 'blur' }],
  carouselRank: [{ required: true, message: '请输入排序值', trigger: 'blur' }]
}

const dialogVisible = ref(false)
const open = async (id) => {
  dialogVisible.value = true
  if (formRef.value) {
    formRef.value.resetFields()
  }

  if (id) {
    const res = await getCarouselByIdApi(id)
    formData.value = res.data.data
    imgUrl.value = formData.value.carouselUrl
  } else {
    imgUrl.value = ''
  }
}

const handleSelectionChange = (e) => {
  ids.value = e

  // ids.value = e
}

// 本地文件预览
const imgUrl = ref('')
const onUpload = async (uploadFile) => {
  imgUrl.value = ''
  // console.log(uploadFile) // uploadFile.raw 就可以获取到上传的文件对象了
  // URL.createObjectURL(文件对象)  可以返回一个可供本地预览的文件地址
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  // 将文件对象赋值给 formModel 作为请求数据
  const fileData = new FormData()
  fileData.append('file', uploadFile.raw)
  // console.log(formData)
  const res = await uploadFileApi(fileData)
  formData.value.carouselUrl = res.data.data
}
const onSubmit = async () => {
  await formRef.value.validate()
  console.log(formData.value)

  if (!formData.value.id) {
    // 新增
    await addCarouselApi(formData.value)
  } else {
    // 修改
    await updateCarouselApi(formData.value)
  }
  dialogVisible.value = false
  ElMessage({
    message: formData.value.id ? '修改成功' : '新增成功',
    type: 'success'
  })
  getCarouselList()
}
</script>

<template>
  <div class="page">
    <TabComponent
      :tableData="tableData"
      :height="500"
      :columns="columns"
      @selectionChange="handleSelectionChange"
    >
      <template #header>
        <el-button type="primary" :icon="Plus" @click="open(null)"
          >新增</el-button
        >
        <el-button type="danger" :icon="Delete" @click="onDelete(null)"
          >批量删除</el-button
        >
      </template>
      <template #operate="{ row }">
        <el-button type="primary" link :icon="Edit" @click="open(row.id)"
          >编辑</el-button
        >
        <el-button type="danger" link :icon="Delete" @click="onDelete(row.id)"
          >删除</el-button
        >
      </template>

      <template #pagination>
        <el-pagination
          background
          layout="sizes,prev, pager, next,total"
          :total="total"
          :page-sizes="[10, 15, 20]"
          v-model:page-size="params.pageSize"
          v-model:current-page="params.pageNo"
          @current-change="currentChange"
          @size-change="sizeChange"
        />
      </template>
    </TabComponent>
    <!-- 弹层 -->
    <div>
      <el-dialog
        v-model="dialogVisible"
        :title="formData.id ? '修改轮播图' : '新增轮播图'"
        width="500"
      >
        <div class="form-box">
          <el-form
            ref="formRef"
            style="max-width: 22rem"
            :model="formData"
            :rules="formRules"
            label-width="auto"
            class="demo-ruleForm"
          >
            <el-form-item label="图片" prop="carouselUrl">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="onUpload"
              >
                <img v-if="imgUrl" :src="imgUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="跳转链接" prop="redirectUrl">
              <el-input
                type="textarea"
                resize="none"
                :autosize="{ minRows: 2, maxRows: 4 }"
                v-model="formData.redirectUrl"
              />
            </el-form-item>
            <el-form-item label="排序值" prop="carouselRank">
              <el-input
                v-model="formData.carouselRank"
                type="number"
                :min="0"
              />
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="onSubmit">
              {{ formData.id ? '修改' : '新增' }}
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style lang="scss" scoped>
/* 文件上传样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 6.25rem;
      height: 6.25rem;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 24px;
      color: #8c939d;
      width: 6.25rem;
      height: 6.25rem;
      text-align: center;
    }
  }
}
</style>
